package com.huangpuweb.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Charsets;
import com.huangpuweb.api.Constants;
import com.huangpuweb.api.model.*;
import com.huangpuweb.api.service.ApiService;
import com.huangpuweb.api.service.CrowdSituationApiService;
import com.huangpuweb.api.service.SyncScenicSpotService;
import com.huangpuweb.api.util.DateUtil;
import com.huangpuweb.api.util.MapUtil;
import com.huangpuweb.api.util.StringUtil;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;
import java.util.List;


/**
 * 开放首页接口
 */
@Controller
@RequestMapping(value = "/api")
public class ApiController {

    private static Logger logger = Logger.getLogger(ApiController.class);

    private ApiService apiService;

    @Autowired
    public void setApiService(ApiService apiService) {
        this.apiService = apiService;
    }


    private CrowdSituationApiService crowdSituationApiService;

    @Autowired
    public void setCrowdSituationApiService(CrowdSituationApiService crowdSituationApiService) {
        this.crowdSituationApiService = crowdSituationApiService;
    }


    /**
     * 垃圾检测推送事件的接口
     */
    @RequestMapping(value = "/getLaJiEventDataPush")
    public void getLaJiEventDataPush(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        JSONObject resultObj = new JSONObject();
        JSONObject resultJson = new JSONObject();

        String str = getRequestBodyString(req);
        JSONObject reqjson = JSONObject.parseObject(str);

        //事件图片的url
        String url = reqjson.getString("url");
        //设备IDgetXiaoGongChengUrl
        String deviceId = reqjson.getString("deviceId");
        //设备名称
        String deviceName = reqjson.getString("deviceName");
        //所在区域
        String area = reqjson.getString("area");
        //事件类型
        String eventType = reqjson.getString("eventType");
        //事件发生的时间
        String eventTime = reqjson.getString("eventTime");

        long time = (long) System.currentTimeMillis() / 1000;

        try {

            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            HttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();


            try {
                //获取图片存放路径
                String imgPath = "/home/software/HuangpuWebApi/images/" + time + ".jpg";
                InputStream inStream = entity.getContent();
                FileOutputStream fw = new FileOutputStream(imgPath, false);
                int b = inStream.read();
                while (b != -1) {
                    fw.write(b);
                    b = inStream.read();
                }
                fw.close();
                EntityUtils.consume(entity);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }


        } catch (IOException e) {

        }

        url = "http://172.82.4.51:8080/images/" + time + ".jpg";
        crowdSituationApiService.insertNewLjEventData(url, deviceId, deviceName, area, eventType, eventTime);

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "上传成功");
        responseData(resultObj.toString(), resp);
        return;

    }


    /**
     * 获取图片访问链接
     */
    @RequestMapping(value = "/getXiaoGongChengImageByName")
    public void getXiaoGongChengImageByName(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        JSONObject resultObj = new JSONObject();
        JSONObject resultJson = new JSONObject();

//        String str = getRequestBodyString(req);
//        JSONObject reqjson = JSONObject.parseObject(str);
//        //范围名称
//        String name = reqjson.getString("name");
        String name = req.getParameter("name");
//        resp.sendRedirect( "http://11.66.236.1:9903/gongdi/file/"+name);

        String content = "";
        LogFactory.getLog(this.getClass()).info("------getXiaoGongChengUrlByName-----start-------");
        try {
            String url = "http://11.66.236.1:9903/gongdi/file/" + name;
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            HttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();


            try {
                //获取图片存放路径
                String imgPath = "/home/software/HuangpuWebApi/images/" + name;
                InputStream inStream = entity.getContent();
                FileOutputStream fw = new FileOutputStream(imgPath, false);
                int b = inStream.read();
                while (b != -1) {
                    fw.write(b);
                    b = inStream.read();
                }
                fw.close();
                EntityUtils.consume(entity);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }


        } catch (IOException e) {
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取成功");
            resultObj.put("data", content);
            responseData(resultObj.toString(), resp);
            return;
        }
//        responseData(content.toString(), resp);

        resp.sendRedirect("http://172.82.4.51:8080/images/" + name);
    }


    /**
     * 小型工地获取列表
     */
    @RequestMapping(value = "/getXiaoGongChengUrlByName")
    public void getXiaoGongChengUrlByName(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        JSONObject resultObj = new JSONObject();
        JSONObject resultJson = new JSONObject();

        String str = getRequestBodyString(req);
        JSONObject reqjson = JSONObject.parseObject(str);

        //范围名称
        String name = reqjson.getString("name");

        String content = "";
        LogFactory.getLog(this.getClass()).info("------getXiaoGongChengUrlByName-----start-------");
        try {
            String url = "http://173.82.57.48:8082/wx/getGongdi_info_ByNameAndState?prj_name=" + name + "&prj_state=6,7";
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            HttpResponse response = httpClient.execute(get);
            content = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取成功");
            resultObj.put("data", content);
            responseData(resultObj.toString(), resp);
            return;
        }
        responseData(content.toString(), resp);

    }


    /**
     * 小型工地获取列表
     */
    @RequestMapping(value = "/getXiaoGongChengUrl")
    public void getXiaoGongChengUrl(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        JSONObject resultObj = new JSONObject();
        JSONObject resultJson = new JSONObject();

        String content = "";
        LogFactory.getLog(this.getClass()).info("------getAliPresonNjdl-----start-------");
        try {
            String url = "http://173.82.57.48:8082/wx/webGetGongdi_AllBySortDate";
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            HttpResponse response = httpClient.execute(get);
            content = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取成功");
            resultObj.put("data", content);
            responseData(resultObj.toString(), resp);
            return;
        }
        responseData(content.toString(), resp);

    }


    /**
     * 阿里南京路撒点（南京路，外滩 todo）
     */
    @RequestMapping(value = "/getAliPresonNjdl")
    public void getAliPresonNjdl(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        JSONObject resultObj = new JSONObject();
        JSONObject resultJson = new JSONObject();

        String str = getRequestBodyString(req);
        JSONObject reqjson = JSONObject.parseObject(str);

        //范围名称
        String type = reqjson.getString("type");
        String content = "";
        LogFactory.getLog(this.getClass()).info("------getAliPresonNjdl-----start-------");
        try {
            String url = "http://215.0.0.31:8085/person/all/" + type;
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            //httpClient防止HTTP/1.1 500 Internal Server Error
            get.addHeader(HttpHeaders.CONTENT_TYPE, "text/xml; charset=utf-8");
            HttpResponse response = httpClient.execute(get);
            content = EntityUtils.toString(response.getEntity(),"UTF-8");
        } catch (IOException e) {
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取成功");
            resultObj.put("data", content);
            responseData(resultObj.toString(), resp);
            return;
        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", content);
        responseData(resultObj.toString(), resp);

    }

    /**
     * 阿里点位人数接口  人口密度2
     */
    @RequestMapping(value = "/getAliPersonSum")
    public void getAliPersonSum(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        JSONObject reqjson = JSONObject.parseObject(str);

        //范围名称
        String camera_id = reqjson.getString("cameraId");
        String content = "";
        LogFactory.getLog(this.getClass()).info("------getAliPersonSum-----start-------");
        try {
            String url = "http://215.0.0.31:8085/person/sum/" + camera_id;
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            HttpResponse response = httpClient.execute(get);
            content = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            responseData(resultObj.toString(), resp);
            return;
        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", JSON.parseObject(content).getString("sum"));
        responseData(resultObj.toString(), resp);

    }

    /**
     * 阿里点位覆盖面积接口  http://215.0.0.31:8085/online_camera  人口密度1
     */
    @RequestMapping(value = "/getAliPersonVideoArea")
    public void getAliPersonVideoArea(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        JSONObject resultObj = new JSONObject();
        JSONObject resultJson = new JSONObject();

        String str = getRequestBodyString(req);
        JSONObject reqjson = JSONObject.parseObject(str);

        //范围名称
        String cameraId = reqjson.getString("cameraId");
        String content = "";
        LogFactory.getLog(this.getClass()).info("------getAliPersonVideoArea-----start-------");
        try {
            String url = "http://215.0.0.31:8085/video_area/" + cameraId;
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            HttpResponse response = httpClient.execute(get);
            content = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取失败");
            resultObj.put("data", content);
            responseData(resultObj.toString(), resp);
            return;
        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        if (content != null) {
            resultObj.put("data", content);
        } else {
            resultObj.put("data", 0);
        }
        responseData(resultObj.toString(), resp);

    }


    /**
     * 阿里南京路预测（南京路，外滩）
     */
    @RequestMapping(value = "/getAliPreNjdl")
    public void getAliPreNjdl(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        JSONObject resultObj = new JSONObject();
        JSONObject resultJson = new JSONObject();

        String str = getRequestBodyString(req);
        JSONObject reqjson = JSONObject.parseObject(str);

        //范围名称
        String type = reqjson.getString("type");
        String content = "";
        LogFactory.getLog(this.getClass()).info("------getAliPreNjdl-----start-------");
        try {
            String url = "http://215.0.0.31:8085/pred/global_estimate/area/" + type;
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            //httpClient防止HTTP/1.1 500 Internal Server Error
            get.addHeader(HttpHeaders.CONTENT_TYPE, "text/xml; charset=utf-8");
            HttpResponse response = httpClient.execute(get);
            content = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取成功");
            resultObj.put("data", content);
            responseData(resultObj.toString(), resp);
            return;
        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", content);
        responseData(resultObj.toString(), resp);

    }

    /**
     * 阿里南京路客流疏散
     */
    @RequestMapping(value = "/getAliEvacuation")
    public void getAliEvacuation(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        JSONObject reqjson = JSONObject.parseObject(str);
        JSONObject jsonObject=new JSONObject();
        //people 实时人数，flows
        String people_num = reqjson.getString("people");
        String flows_in = reqjson.getString("flows");
        String content = "";
        LogFactory.getLog(this.getClass()).info("------getAliPreNjdl-----start-------");
        try {
            String url = "http://215.0.0.31:8085/evacuation?flows_in=" + flows_in+"&people_num="+people_num;
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            HttpResponse response = httpClient.execute(get);
            content = EntityUtils.toString(response.getEntity());
            jsonObject = JSON.parseObject(content);

        } catch (IOException e) {
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取失败");
            resultObj.put("data", jsonObject);
            responseData(resultObj.toString(), resp);
            return;
        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", jsonObject);
        responseData(resultObj.toString(), resp);

    }
    /**
     * 阿里路口信息，四个路口
     */
    @RequestMapping(value = "/getAliRoad")
    public void getAliRoad(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        JSONObject resultObj = new JSONObject();
        String content = "";
        LogFactory.getLog(this.getClass()).info("------getAliPreNjdl-----start-------");
        try {
            String url = "http://215.0.0.31:8085/stat/global_estimate/cross";
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            HttpResponse response = httpClient.execute(get);
            content = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取失败");
            resultObj.put("data", content);
            responseData(resultObj.toString(), resp);
            return;
        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", JSON.parseArray(content));
        responseData(resultObj.toString(), resp);

    }

    /**
     * top5事件
     */
    @RequestMapping(value = "/getXuJianTop5")
    public void getXuJianTop5(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        JSONObject resultObj = new JSONObject();
        JSONObject resultJson = new JSONObject();
        String content = "";
        LogFactory.getLog(this.getClass()).info("------getXuJianTop5-----start-------");
        try {

            HttpClient httpclient = new DefaultHttpClient();
            //HttpPost httpPost = new HttpPost("http://173.82.57.46:9999/ecis-access/api/event/getLatestFiveEvent");
            HttpPost httpPost = new HttpPost("http://173.82.57.47:9989/ecis-access/api/event/getLatestFiveEvent");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key", "XJYJ_2020_XZJSC");
            StringEntity s = new StringEntity(jsonObject.toString());
            s.setContentEncoding("utf-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            httpPost.setEntity(s);
            HttpResponse res = httpclient.execute(httpPost);
            content = EntityUtils.toString(res.getEntity());


        } catch (IOException e) {
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取成功");
            resultObj.put("data", content);
            responseData(resultObj.toString(), resp);
            return;
        }


        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", content);
        responseData(resultObj.toString(), resp);

    }


    /**
     * 根据消防站位置解析经纬度
     */
    @RequestMapping(value = "/operateLngLatByFirControlAddress")
    public void operateLngLatByStreetAddress(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        HttpClient client = HttpClientBuilder.create().build();
        List<SysMiniFireControl> listSysMiniFireControl = crowdSituationApiService.getListSysMiniFireControl();
        JSONArray ja = new JSONArray();
        JSONObject jo = null;
        JSONObject jb = null;
        JSONObject locationjson = null;
        for (SysMiniFireControl s : listSysMiniFireControl) {


            // 根据URL创建HttpGet实例
            //http://172.82.4.1:8070
            //173.82.57.8:8070
            try {
                HttpGet get = new HttpGet("http://api.map.baidu.com/geocoder?address=上海市黄浦区" + s.getSite_adress() + "&output=json&key=PyLa5E6K6BEGI0euwz1s9dWc&city=上海市");
                // 执行get请求，得到返回体
                HttpResponse response = client.execute(get);
                // 判断是否正常返回
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 解析数据
                    String data = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
                    jo = JSONObject.parseObject(data);
                    if (jo.get("status").equals("OK")) {
                        jb = jo.getJSONObject("result");
                        locationjson = jb.getJSONObject("location");
                        System.out.println(s.getSite_adress() + "----" + locationjson.getString("lng") + "------" + locationjson.getString("lat"));
                        crowdSituationApiService.updateSysFireLngLatById(locationjson.getString("lng"), locationjson.getString("lat"), s.getId());
                    }
                }
            } catch (Exception e) {
                continue;
            }

//                        }    sysHpEmergencyEvent.setBaiduLongitude(locationjson.getString("lng"));
//                            sysHpEmergencyEvent.setBaiduLatitude(locationjson.getString("lat"));


        }


    }



    /**
     * 收运地点解析经纬度
     */
    @RequestMapping(value = "/shouYunAddress")
    public void operateLngLatByShouYunAddress(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        HttpClient client = HttpClientBuilder.create().build();
        List<HpJcgsdssms> listHpJcgsdssms = crowdSituationApiService.getHpJcgsdssms();
        JSONArray ja = new JSONArray();
        JSONObject jo = null;
        JSONObject jb = null;
        JSONObject locationjson = null;
        for (HpJcgsdssms s : listHpJcgsdssms) {
            // 根据URL创建HttpGet实例
            //http://172.82.4.1:8070
            //173.82.57.8:8070
            try {
                HttpGet get = new HttpGet("http://api.map.baidu.com/geocoder?address=上海市黄浦区" + s.getAddress() + "&output=json&key=PyLa5E6K6BEGI0euwz1s9dWc&city=上海市");
                // 执行get请求，得到返回体
                HttpResponse response = client.execute(get);
                // 判断是否正常返回
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 解析数据
                    String data = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
                    jo = JSONObject.parseObject(data);
                    if (jo.get("status").equals("OK")) {
                        jb = jo.getJSONObject("result");
                        locationjson = jb.getJSONObject("location");
                        System.out.println(s.getAddress() + "----" + locationjson.getString("lng") + "------" + locationjson.getString("lat"));
                        double[] doubles= MapUtil.bd09towgs84(Double.valueOf(locationjson.getString("lng")), Double.valueOf(locationjson.getString("lat")));
                        crowdSituationApiService.updateHpJcgsdssms(String.valueOf(doubles[0]), String.valueOf(doubles[1]), s.getId());
                    }
                }
            } catch (Exception e) {
                continue;
            }

//                        }    sysHpEmergencyEvent.setBaiduLongitude(locationjson.getString("lng"));
//                            sysHpEmergencyEvent.setBaiduLatitude(locationjson.getString("lat"));


        }


    }

    /**
     * 消防数据总览
     *
     * @return
     */
    @RequestMapping(value = "/fireapioverview")
    public void fireapioverview(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        LogFactory.getLog(this.getClass()).info("------fireapioverview-----start-------");
        JSONObject result = null;
        long time = (long) System.currentTimeMillis() / 1000;
        String str = "c8e45be7a47c4ba692effd3b2d2f543eapp_keybda5d74d824d46f48471a3e9f24ed299formatjsonsign_methodmd5timestamp" + time + "v1.0c8e45be7a47c4ba692effd3b2d2f543e";
        String sign = DigestUtils.md5DigestAsHex(str.getBytes()).toUpperCase();
        try {
            String url = "http://172.82.16.1/city_center/city/overview";
            JSONObject json = new JSONObject();
            json.put("app_key", "bda5d74d824d46f48471a3e9f24ed299");
            json.put("format", "json");
            json.put("sign", sign);
            json.put("sign_method", "md5");
            json.put("timestamp", time);
            json.put("v", "1.0");
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            StringEntity postingString = new StringEntity(json.toJSONString());
            post.setEntity(postingString);
            post.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(post);
            String content = EntityUtils.toString(response.getEntity());

            result = (JSONObject) JSONObject.parse(content);

        } catch (IOException e) {
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取成功");
            resultObj.put("data", result);
            responseData(resultObj.toString(), resp);
            return;
        }


        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", result);
        responseData(resultObj.toString(), resp);

    }


    /**
     * 消防互联网各街道报警数量
     *
     * @return
     */
    @RequestMapping(value = "/fireapistreetAlarm")
    public void fireapistreetAlarm(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        LogFactory.getLog(this.getClass()).info("------fireapistreetAlarm-----start-------");

        JSONObject result = null;
        long time = (long) System.currentTimeMillis() / 1000;
        String str = "c8e45be7a47c4ba692effd3b2d2f543eapp_keybda5d74d824d46f48471a3e9f24ed299formatjsonsign_methodmd5timestamp" + time + "v1.0c8e45be7a47c4ba692effd3b2d2f543e";
        String sign = DigestUtils.md5DigestAsHex(str.getBytes()).toUpperCase();
        try {
            String url = "http://172.82.16.1/city_center/city/streetAlarm";
            JSONObject json = new JSONObject();
            json.put("app_key", "bda5d74d824d46f48471a3e9f24ed299");
            json.put("format", "json");
            json.put("sign", sign);
            json.put("sign_method", "md5");
            json.put("timestamp", time);
            json.put("v", "1.0");
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            StringEntity postingString = new StringEntity(json.toJSONString());
            post.setEntity(postingString);
            post.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(post);
            String content = EntityUtils.toString(response.getEntity());

            result = (JSONObject) JSONObject.parse(content);

        } catch (IOException e) {
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取成功");
            resultObj.put("data", result);
            responseData(resultObj.toString(), resp);
            return;
        }

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", result);
        responseData(resultObj.toString(), resp);

    }


    /**
     * 消防互联网报警督察统计
     *
     * @return
     */
    @RequestMapping(value = "/fireapialarmStatistics")
    public void fireapialarmStatistics(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        LogFactory.getLog(this.getClass()).info("------fireapialarmStatistics-----start-------");

        JSONObject result = null;
        long time = (long) System.currentTimeMillis() / 1000;
        String str = "c8e45be7a47c4ba692effd3b2d2f543eapp_keybda5d74d824d46f48471a3e9f24ed299formatjsonsign_methodmd5timestamp" + time + "v1.0c8e45be7a47c4ba692effd3b2d2f543e";
        String sign = DigestUtils.md5DigestAsHex(str.getBytes()).toUpperCase();
        try {
            String url = "http://172.82.16.1/city_center/city/alarmStatistics";
            JSONObject json = new JSONObject();
            json.put("app_key", "bda5d74d824d46f48471a3e9f24ed299");
            json.put("format", "json");
            json.put("sign", sign);
            json.put("sign_method", "md5");
            json.put("timestamp", time);
            json.put("v", "1.0");
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            StringEntity postingString = new StringEntity(json.toJSONString());
            post.setEntity(postingString);
            post.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(post);
            String content = EntityUtils.toString(response.getEntity());

            result = (JSONObject) JSONObject.parse(content);

        } catch (IOException e) {
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取成功");
            resultObj.put("data", result);
            responseData(resultObj.toString(), resp);
            return;
        }

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", result);
        responseData(resultObj.toString(), resp);

    }


    /**
     * 消防建筑群信息
     *
     * @return
     */
    @RequestMapping(value = "/fireapibuildingGroupGis")
    public void fireapibuildingGroupGis(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        LogFactory.getLog(this.getClass()).info("------fireapibuildingGroupGis-----start-------");

        JSONObject result = null;
        long time = (long) System.currentTimeMillis() / 1000;
        String str = "c8e45be7a47c4ba692effd3b2d2f543eapp_keybda5d74d824d46f48471a3e9f24ed299formatjsonsign_methodmd5timestamp" + time + "v1.0c8e45be7a47c4ba692effd3b2d2f543e";
        String sign = DigestUtils.md5DigestAsHex(str.getBytes()).toUpperCase();
        try {
            String url = "http://172.82.16.1/city_center/city/buildingGroupGis";
            JSONObject json = new JSONObject();
            json.put("app_key", "bda5d74d824d46f48471a3e9f24ed299");
            json.put("format", "json");
            json.put("sign", sign);
            json.put("sign_method", "md5");
            json.put("timestamp", time);
            json.put("v", "1.0");
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            StringEntity postingString = new StringEntity(json.toJSONString());
            post.setEntity(postingString);
            post.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(post);
            String content = EntityUtils.toString(response.getEntity());

            result = (JSONObject) JSONObject.parse(content);

        } catch (IOException e) {
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取成功");
            resultObj.put("data", result);
            responseData(resultObj.toString(), resp);
            return;
        }

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", result);
        responseData(resultObj.toString(), resp);

    }


    /**
     * 分建筑群概况
     *
     * @return
     */
    @RequestMapping(value = "/fireapibuildingGroupInfo")
    public void fireapibuildingGroupInfo(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        JSONObject jsonObject = null;

        LogFactory.getLog(this.getClass()).info("------fireapibuildingGroupInfo-----start-------");
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject reqjson = JSONObject.parseObject(str);

        //范围名称
        String pid = reqjson.getString("pid");
        JSONObject result = null;

        long time = (long) System.currentTimeMillis() / 1000;
        String string = "c8e45be7a47c4ba692effd3b2d2f543eapp_keybda5d74d824d46f48471a3e9f24ed299formatjsonpid" + pid + "sign_methodmd5timestamp" + time + "v1.0c8e45be7a47c4ba692effd3b2d2f543e";
        String sign = DigestUtils.md5DigestAsHex(string.getBytes()).toUpperCase();
        JSONObject jsonObject1=new JSONObject();
        try {
            String url = "http://172.82.16.1/city_center/city/buildingGroupInfo";
            JSONObject json = new JSONObject();
            json.put("app_key", "bda5d74d824d46f48471a3e9f24ed299");
            json.put("format", "json");
            json.put("sign", sign);
            json.put("sign_method", "md5");
            json.put("timestamp", time);
            json.put("v", "1.0");
            json.put("pid", pid);
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            StringEntity postingString = new StringEntity(json.toJSONString());
            post.setEntity(postingString);
            post.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(post);
            String content = EntityUtils.toString(response.getEntity());
            String aNull = content.replaceAll("null", "0");
            result = (JSONObject) JSONObject.parse(aNull);
        } catch (IOException e) {
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取失败");
            responseData(resultObj.toString(), resp);
            return;
        }

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", result);
        responseData(resultObj.toString(), resp);

    }


    //读取json文件
    public static String readJsonFile(String fileName) {
        File file = new File("F:/" + fileName);
        StringBuilder localStrBulider = new StringBuilder();
        if (file.isFile() && file.exists()) {
            try {
                InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "utf-8");
                BufferedReader bufferReader = new BufferedReader(inputStreamReader);
                String lineStr = null;
                try {
                    while ((lineStr = bufferReader.readLine()) != null) {
                        localStrBulider.append(lineStr);
                    }
                    bufferReader.close();
                    inputStreamReader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    System.out.println("file read error!");
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                System.out.println("file catch unsupported encoding!");
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                System.out.println("file not found!");
                e.printStackTrace();
            }
        } else {
            System.out.println("file is not a file or file is not existing!");
            return null;
        }
        return localStrBulider.toString();
    }


    /**
     * 读取文件
     *
     * @return List<Record>
     */
    @RequestMapping(value = "/readFile")
    public void readFile(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        LogFactory.getLog(this.getClass()).info("------readFile-----start-------");

        String s = readJsonFile("hproad.json");
        JSONObject jobj = JSON.parseObject(s);
        JSONArray movies = jobj.getJSONArray("features");//构建JSONArray数组
        for (int i = 0; i < movies.size(); i++) {
            try {
                JSONObject key = (JSONObject) movies.get(i);
                JSONObject json = key.getJSONObject("geometry");
                String coordinates = json.getString("coordinates");
                JSONObject propertiesjson = key.getJSONObject("properties");
                String inter_id = propertiesjson.getString("inter_id");
                String inter_name = propertiesjson.getString("inter_name");
                String rid_name = propertiesjson.getString("rid_name");
                String rid = propertiesjson.getString("rid");
                System.out.println("rid-------" + rid);
                crowdSituationApiService.insertNewHpRoad(coordinates, inter_id, inter_name, rid, rid_name);
            } catch (Exception e) {
                System.out.println("error-------");
                continue;
            }

        }


    }

    @Resource
    private SyncScenicSpotService syncScenicSpotService;
    /**
     * 首页客流数据
     *
     * @return List<Record>
     */
    @RequestMapping(value = "/flowData")
    public void flowData(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();

        LogFactory.getLog(this.getClass()).info("------flowData-----start-------");


        String[] spotcodeArr = Constants.SPOTCODELIST.split(",");

        SysRefinedCrowdSituation ss = new SysRefinedCrowdSituation();
        SysRefinedCrowdSituation maxss = new SysRefinedCrowdSituation();
//        SysHistoryCrowdSituation lastdayss = new SysHistoryCrowdSituation();
//        SysHistoryCrowdSituation yearandMonth = new SysHistoryCrowdSituation();
//        SysHistoryCrowdSituation monthOnMonth = new SysHistoryCrowdSituation();
//        CrowdSysSetting crowdSysSetting = new CrowdSysSetting();
        //获取今日0点
        String todayZero = DateUtil.getToday23(0, 0, 0);
        JSONArray jsonArray = new JSONArray();
        HpScenicRealTime hList = null;
        HpScenicRealTime max = null;
        JSONObject jsonObject = null;
        for (int i = 0; i < spotcodeArr.length; i++) {
            jsonObject = new JSONObject();
//            crowdSysSetting = crowdSituationApiService.getCrowdSysSettingBySpotCode(spotcodeArr[i]);
            if (spotcodeArr[i].equals("SHHPQ_YUYUAN_WAIQUAN")) {
                hList = syncScenicSpotService.getAllSpot("YUYUAN");
                max = syncScenicSpotService.getTodayMax(todayZero, "YUYUAN");
            } else if (spotcodeArr[i].equals("SHHPQ_WAITAN")) {
                hList = syncScenicSpotService.getAllSpot("WAITAN");
                max = syncScenicSpotService.getTodayMax(todayZero, "WAITAN");
            } else if (spotcodeArr[i].equals("SHHPQ_XINTIANDI")) {
                hList = syncScenicSpotService.getAllSpot("XINTIANDI");
                max = syncScenicSpotService.getTodayMax(todayZero, "XINTIANDI");
            } else if (spotcodeArr[i].equals("SHHPQ_TIANZIFANG")) {
                hList = syncScenicSpotService.getAllSpot("TIANZIFANG");
                max = syncScenicSpotService.getTodayMax(todayZero, "TIANZIFANG");
            }
            //获取景区名称、景区编码、实时人流、累计人流
            ss = crowdSituationApiService.getAllDataRecordBack(spotcodeArr[i]);
            //获取当日人流峰值
            maxss = crowdSituationApiService.getMaxNumberRecord(todayZero, spotcodeArr[i]);
            if (maxss == null) {
                //设置今日人流峰值
                jsonObject.put("maxNumber", 0);
                //设置峰值时间
                jsonObject.put("maxTime", 0);
            } else {
//                String hour = DateUtil.getHM(maxss.getCreateTime());
//                //设置今日人流峰值
//                jsonObject.put("maxNumber", maxss.getRealtimeNumber());
//                //设置峰值时间
//                jsonObject.put("maxTime", hour);
                if (max != null && max.getCreateTime() != null) {
                    String hours = max.getCreateTime().substring(11, 16);
                    jsonObject.put("maxNumber", max.getRealtimenumber());
                    jsonObject.put("maxTime", hours);
                }
                if (maxss != null && maxss.getCreateTime() != null) {
                    String hour = maxss.getCreateTime().substring(11, 16);

                    //设置今日人流峰值,峰值时间
                    if (maxss.getSpotCode().equals("SHHPQ_YUYUAN_NEIQUAN") || maxss.getSpotCode().equals("SHHPQ_NANJINGLU") || maxss.getSpotCode().equals("SHHPQ_NANJINGLUDONGTUO")) {
                        jsonObject.put("maxNumber", maxss.getRealtimeNumber());
                        jsonObject.put("maxTime", hour);
                    }
                }
            }
            String level=null;
            if (ss == null) {

                //设置实时客流量
                jsonObject.put("realtime_number", 0);
                jsonObject.put("spot_name", 0);
                jsonObject.put("record_time", 0);
                jsonObject.put("level", 0);
                jsonObject.put("spotCode", 0);
                jsonObject.put("total_number", 0);
            } else {
                if (ss.getSpotCode().equals("SHHPQ_YUYUAN_WAIQUAN")||ss.getSpotCode().equals("SHHPQ_WAITAN")||ss.getSpotCode().equals("SHHPQ_XINTIANDI")||ss.getSpotCode().equals("SHHPQ_TIANZIFANG")) {
                    level = judgeLevel(ss.getSpotCode(), Integer.valueOf(hList.getRealtimenumber()));
                    jsonObject.put("realtime_number", hList.getRealtimenumber());
                    jsonObject.put("total_number", hList.getTotalnumber());
                    if (ss.getSpotCode().equals("SHHPQ_YUYUAN_WAIQUAN")) {
                        jsonObject.put("spot_name", "豫园（外圈）");
                    } else if (ss.getSpotCode().equals("SHHPQ_WAITAN")) {
                        jsonObject.put("spot_name", "外滩");
                    } else if (ss.getSpotCode().equals("SHHPQ_XINTIANDI")) {
                        jsonObject.put("spot_name", "新天地");
                    } else if (ss.getSpotCode().equals("SHHPQ_TIANZIFANG")) {
                        jsonObject.put("spot_name", "田子坊");
                    }
                }else {
                    level = judgeLevel(ss.getSpotCode(), ss.getRealtimeNumber());
                    jsonObject.put("spot_name", ss.getSpotName());
                    jsonObject.put("realtime_number", ss.getRealtimeNumber());
                    jsonObject.put("record_time", ss.getUpdateTime());
                    jsonObject.put("total_number", ss.getTotalNumber());

                }
                //设置实时客流量
//                jsonObject.put("realtime_number", ss.getRealtimeNumber());
//                jsonObject.put("spot_name", ss.getSpotName());
//                jsonObject.put("record_time", ss.getUpdateTime());
                jsonObject.put("level", level);
                jsonObject.put("spotCode", ss.getSpotCode());
//                jsonObject.put("total_number", ss.getTotalNumber());
            }

            jsonArray.add(jsonObject);
        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", jsonArray);
        responseData(resultObj.toString(), resp);

    }

    /**
     * 获取视频列表
     */
    @RequestMapping("getAllVideoList")
    public void getAllVideoList(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String videoScenic = jsonObject.getString("VideoScenic");
        List<BatchStreamStatus> statusList = apiService.getAllVideoList(videoScenic);
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", statusList);
        responseData(resultObj.toString(), resp);
    }

    /**
     * 计算风险等级
     *
     * @param spotCode       景区编码
     * @param realtimeNumber 实时客流
     * @return String
     */
    private String judgeLevel(String spotCode, int realtimeNumber) {
        String level = null;
        switch (spotCode) {
            case "SHHPQ_WAITAN":
                if (realtimeNumber < 10000) {
                    level = "四级";
                } else if (realtimeNumber >= 10000 && realtimeNumber < 15000) {
                    level = "三级";
                } else if (realtimeNumber >= 15000 && realtimeNumber < 20000) {
                    level = "二级";
                } else {
                    level = "一级";
                }
                break;
            case "SHHPQ_NANJINGLU":
                if (realtimeNumber < 10000) {
                    level = "四级";
                } else if (realtimeNumber >= 10000 && realtimeNumber < 15000) {
                    level = "三级";
                } else if (realtimeNumber >= 15000 && realtimeNumber < 20000) {
                    level = "二级";
                } else {
                    level = "一级";
                }
                break;
            case "SHHPQ_TIANZIFANG":
                if (realtimeNumber < 2000) {
                    level = "四级";
                } else if (realtimeNumber >= 2000 && realtimeNumber < 4000) {
                    level = "三级";
                } else if (realtimeNumber >= 4000 && realtimeNumber < 5000) {
                    level = "二级";
                } else {
                    level = "一级";
                }
                break;
            case "SHHPQ_XINTIANDI":
                if (realtimeNumber < 2000) {
                    level = "四级";
                } else if (realtimeNumber >= 2000 && realtimeNumber < 4000) {
                    level = "三级";
                } else if (realtimeNumber >= 4000 && realtimeNumber < 7000) {
                    level = "二级";
                } else {
                    level = "一级";
                }
                break;
            case "SHHPQ_YUYUAN_NEIQUAN":
                if (realtimeNumber < 20000) {
                    level = "四级";
                } else if (realtimeNumber >= 20000 && realtimeNumber < 30000) {
                    level = "三级";
                } else if (realtimeNumber >= 30000 && realtimeNumber < 40000) {
                    level = "二级";
                } else {
                    level = "一级";
                }
                break;
            case "SHHPQ_YUYUAN_WAIQUAN":
                if (realtimeNumber < 20000) {
                    level = "四级";
                } else if (realtimeNumber >= 20000 && realtimeNumber < 30000) {
                    level = "三级";
                } else if (realtimeNumber >= 30000 && realtimeNumber < 40000) {
                    level = "二级";
                } else {
                    level = "一级";
                }
                break;
        }
        return level;
    }

    /**
     * 从req中读取数据
     *
     * @param req
     * @return
     */
    private String getRequestBodyString(HttpServletRequest req) {
        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(), "utf-8"));
            String line;
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            // e.printStackTrace();
            return null;
        }
        return builder.toString();
    }

    private void responseErrorData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        JSONObject resultObj = new JSONObject();
        resultObj.put("errorcode", 1);
        resultObj.put("message", string);
        responseData(resultObj.toString(), resp);
    }

    private void responseData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        responseDate("application/json;charset=UTF-8", string, resp);

    }

    private void responseDate(String contentType, String value, HttpServletResponse resp) throws Exception {
        resp.setContentType(contentType);
        resp.getWriter().write(value);
    }
}
